package com.eqdd.yiqidian.ui.function.shopping

import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.ProductBean
import com.eqdd.yiqidian.bean.ShoppingProductBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.ui.companyspace.ProDemandInfoActivity
import com.eqdd.yiqidian.ui.companyspace.ProductInfoActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_shopping_main_go.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import java.util.*

/**
 * Created by jhj on 18-9-14.
 */
class GoShoppingMainActivity : BaseActivity() {

    override fun initBinding() {
        setContentView(R.layout.activity_shopping_main_go)
        initTopTitleBar(View.VISIBLE, "易企购")

    }


    override fun initData() {

        //最新产品
        OkGo.post<HttpResult<List<ProductBean>>>(HttpConfig.BASE_URL + HttpConfig.SHOPPING_PRODUCT)
                .params("page", 0)
                .execute(object : JsonCallBack<HttpResult<List<ProductBean>>>() {
                    override fun onSuccess(response: Response<HttpResult<List<ProductBean>>>?) {
                        val result = response?.body()
                        if (result?.status == 200 && result.items != null && result.items.isNotEmpty()) {
                            layout_product_new.visibility = View.VISIBLE
                            recyclerViewManager(recyclerView_product_new)
                            val slimAdapterEx = SlimAdapterEx.create()
                                    .register<ProductBean>(R.layout.list_item_166, SlimInjector<ProductBean> { data, injector ->
                                        data?.let {
                                            product(injector, it.image, it.productName, it.productPrice, it.area)
                                        }
                                    })
                                    .attachTo(recyclerView_product_new)
                                    .updateData(result.items) as SlimAdapterEx<ProductBean>?
                            ItemClickSupport.addTo(recyclerView_product_new)
                                    .setOnItemClickListener { _, position, v ->
                                        val bean = slimAdapterEx?.getDataItem(position)
                                        startActivity<ProductInfoActivity>(Config.ID to bean?.id)
                                    }
                        } else {
                            layout_product_new.visibility = View.GONE
                        }
                    }
                })
        //推荐产品
        productDemand(layout_product_recommend, recyclerView_product_recommend, 0)
        //热门产品
        productDemand(layout_product_hot, recyclerView_product_hot, 1)
        //推荐需求
        productDemand(layout_demand_recommend, recyclerView_demand_recommend, 2)
        //热门需求
        productDemand(layout_demand_hot, recyclerView_demand_hot, 3)
        //最新需求
        OkGo.post<HttpResult<List<ShoppingProductBean>>>(HttpConfig.BASE_URL + HttpConfig.SHOPPING_DEMAND_NEW)
                .params("page", 0)
                .execute(object : JsonCallBack<HttpResult<List<ShoppingProductBean>>>() {
                    override fun onSuccess(response: Response<HttpResult<List<ShoppingProductBean>>>?) {
                        val result = response?.body()
                        if (result?.status == 200 && result.items != null && result.items.isNotEmpty()) {
                            layout_demand_new.visibility = View.VISIBLE
                            recyclerViewManager(recyclerView_demand_new)
                            val slimAdapterEx = SlimAdapterEx.create()
                                    .register<ShoppingProductBean>(R.layout.list_item_150, SlimInjector<ShoppingProductBean> { data, injector ->
                                        data?.let {
                                            //demand(injector, it.productImg ?: "", it.productName, it.productPrice, it.demandAddress)
                                            injector?.text(R.id.tv_content, "【${it.productName}】${it.productType}")
                                        }
                                    })
                                    .attachTo(recyclerView_demand_new)
                                    .updateData(result.items) as SlimAdapterEx<ShoppingProductBean>?
                            ItemClickSupport.addTo(recyclerView_demand_new)
                                    .setOnItemClickListener { _, position, v ->
                                        val bean = slimAdapterEx?.getDataItem(position)
                                        startActivity<ProDemandInfoActivity>(Config.ID to bean?.id, Config.TYPE to 2, "fun" to 2)
                                    }
                        } else {
                            layout_demand_new.visibility = View.GONE
                        }
                    }
                })

    }

    private fun productDemand(linearLayout: LinearLayout, recyclerView: RecyclerView, type: Int) {
        OkGo.post<HttpResult<List<ShoppingProductBean>>>(HttpConfig.BASE_URL + HttpConfig.SHOPPING_PRODUCT_DEMAND)
                .params("type", type)
                .execute(object : JsonCallBack<HttpResult<List<ShoppingProductBean>>>() {
                    override fun onSuccess(response: Response<HttpResult<List<ShoppingProductBean>>>?) {
                        val result = response?.body()
                        if (result?.status == 200 && result.items != null && result.items.isNotEmpty()) {
                            linearLayout.visibility = View.VISIBLE
                            recyclerViewManager(recyclerView)
                            productAdapter(recyclerView, result.items, type)
                        } else {
                            linearLayout.visibility = View.GONE
                        }
                    }
                })
    }

    fun recyclerViewManager(recyclerView: RecyclerView) {
        recyclerView.addItemDecoration(DividerLineItemDecoration(this@GoShoppingMainActivity))
        recyclerView.layoutManager = object : LinearLayoutManager(this@GoShoppingMainActivity) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        recyclerView.isNestedScrollingEnabled = false
        recyclerView.setHasFixedSize(true)
    }


    fun productAdapter(recyclerView: RecyclerView, dataList: List<ShoppingProductBean>, type: Int) {
        val resId = if (type == 0 || type == 1) {
            R.layout.list_item_166
        } else {
            R.layout.list_item_150
        }
        val slimAdapterEx = SlimAdapterEx.create()
                .register<ShoppingProductBean>(resId, SlimInjector<ShoppingProductBean> { data, injector ->
                    data?.let {
                        if (type == 0 || type == 1) {
                            product(injector, it.productImg, it.productName, it.productPrice, it.productArea)
                        } else {
                            //demand(injector, it.productImg, it.productName, it.productPrice, it.productArea)
                            injector?.text(R.id.tv_content, "【${it.productName}】${it.productType}")
                        }
                    }
                })
                .attachTo(recyclerView)
                .updateData(dataList) as SlimAdapterEx<ShoppingProductBean>?
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { _, position, v ->
                    val bean = slimAdapterEx?.getDataItem(position)
                    if (type == 0 || type == 1) {
                        startActivity<ProductInfoActivity>(Config.ID to bean?.productId)
                    } else {
                        startActivity<ProDemandInfoActivity>(Config.ID to bean?.productId, Config.TYPE to 2, "fun" to 2)
                    }
                }
    }

    fun product(injector: IViewInjector<*>?, img: String, name: String, price: Int?, position: String?) {
        val str = String.format(Locale.CHINA, "产品价格：￥%s元", price)
        val span = SpannableString(str)
        span.setSpan(ForegroundColorSpan(Color.RED), 5, str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        injector
                ?.with<ImageView>(R.id.iv_image) { view ->
                    if (img.isNotBlank()) {
                        view.visibility = View.VISIBLE
                        view.onClick {
                            imgPathPreview(img)
                        }
                        Glide.with(this)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(img)
                                .into(view)
                    } else {
                        view.visibility = View.GONE
                    }
                }
                ?.text(R.id.tv_name, String.format(Locale.CHINA, "产品名称：%s", name))
                ?.text(R.id.tv_post, span)
                ?.text(R.id.tv_msg, String.format(Locale.CHINA, "发货地址：%s", position))
    }


    fun demand(injector: IViewInjector<*>?, img: String, name: String, price: Int?, position: String?) {
        val str = String.format(Locale.CHINA, "产品价格：￥%s元", price)
        val span = SpannableString(str)
        span.setSpan(ForegroundColorSpan(Color.RED), 5, str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        injector
                ?.with<ImageView>(R.id.iv_image) { view ->
                    if (img.isNotBlank()) {
                        view.visibility = View.VISIBLE
                        view.onClick {
                            imgPathPreview(img)
                        }
                        Glide.with(this)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(img)
                                .into(view)
                    } else {
                        view.visibility = View.GONE
                    }
                }
                ?.text(R.id.tv_name, String.format(Locale.CHINA, "需求名称：%s", name))
                ?.text(R.id.tv_post, span)
                ?.text(R.id.tv_msg, String.format(Locale.CHINA, "发货地址：%s", position))
    }

    override fun setView() {
        tv_search_product.onClick {
            startActivity<ShoppingProductActivity>()
        }
        tv_search_demand.onClick {
            startActivity<ShoppingDemandActivity>()
        }
    }
}


